from datetime import timedelta

from fastapi import APIRouter, Depends, HTTPException,status
from fastapi.security import OAuth2PasswordRequestForm
from sqlmodel import Session

from ...core.auth import get_user_permissions, get_current_user_with_permissions
from ...core.database import get_session
from ...core.config import settings
from ...core.security import create_access_token
from ...crud.permission import get_user_by_username
from ...schemas.permission import Token


router = APIRouter(prefix="/auth", tags=["认证"])

@router.post("/login", response_model=Token)
async def login(
        form_data: OAuth2PasswordRequestForm = Depends(),
        session: Session = Depends(get_session)
):
    """用户登录"""
    user = get_user_by_username(session, form_data.username)
    if not user or not user.check_password(form_data.password):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail="用户名或密码错误",
                            headers={"WWW-Authenticate": "Bearer"})

    # 获取用户的权限
    permissions = get_user_permissions(session, user)

    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "permissions": permissions},
        expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

@router.get("/me")
async def read_user_me(
        current_user_info: dict = Depends(get_current_user_with_permissions)
):
    """获取当前用户信息和权限"""
    user = current_user_info["user"]
    permissions = current_user_info["permissions"]
    return {
        "user": {
            "id": user.id,
            "username": user.username,
            "full_name": user.full_name,
            "email": user.email,
            "is_active": user.is_active,
            "is_superuser": user.is_superuser
        },
        "permissions": permissions
    }
